<template>
  <div class="comment-item">
    <!-- 评论头部信息 -->
    <div class="comment-header" @click="reply">
      <span class="user-name">{{ comment.userName }}</span>
      <span v-if="comment.replyUserName" class="reply-info">
        回复了
        <span class="reply-user">{{ comment.replyUserName }}</span>
      </span>
      <span class="create-time">{{ comment.commentCreateTime }} IP属地：{{ comment.ipAddress }}</span>
    </div>

    <!-- 评论内容 -->
    <div class="comment-content" @click="reply">
      {{ comment.comment }}
    </div>

    <!-- 评论操作 -->
    <div class="comment-actions">
      <el-button :style="{color: isLiked ?  '#1890ff' : '#666' }"
                 class="like-button"
                 link
                 @click="handleLike">
        <el-icon>
          <ArrowUpBold/>
        </el-icon>
        <span>{{ comment.likeCount }}</span>
      </el-button>
      <el-button class="reply-button" link @click="toggleReplies">
        <el-icon>
          <ChatDotRound/>
        </el-icon>
        <span>{{ comment.replyCount }}</span>
      </el-button>
    </div>

    <!-- 子评论列表 -->
    <div v-if="comment.replyComments && comment.replyComments.length > 0">
      <el-collapse-transition>
        <div v-show="showReplies">
          <SingleComment
              v-for="(reply, index) in visibleReplyComments"
              :key="reply.commentId"
              :comment="reply"
              class="reply-item"
          />
          <!-- 展开更多按钮 -->
          <div v-if="hasMoreReplies" class="load-more" @click="loadMoreReplies">
            <a>点击展开更多</a>
          </div>
        </div>
      </el-collapse-transition>
    </div>
  </div>
</template>

<script>
import {ElMessage, ElMessageBox} from "element-plus";
import {ArrowUpBold, CaretTop, ChatDotRound, Check, Delete} from "@element-plus/icons-vue";
import axios from "axios";
import {debounce} from "lodash";

export default {
  name: "SingleComment",
  components: {
    ArrowUpBold,
    CaretTop,
    Check,
    Delete,
    ChatDotRound,
  },
  props: {
    comment: {
      type: Object,
      required: true,
      userName: ""
    }
  },
  data() {
    return {
      showReplies: false, // 是否显示子评论
      isLiked: false, // 是否已点赞
      likeCount: 0, // 点赞数量
      userId: null, // 用户ID
      relatedCategory: "",
      relatedId: null,
      visibleReplyCount: 3, // 每次显示的子评论数量
    };
  },
  computed: {
    // 计算当前可见的子评论
    visibleReplyComments() {
      return this.comment.replyComments.slice(0, this.visibleReplyCount);
    },
    // 是否还有更多子评论可以展开
    hasMoreReplies() {
      return this.comment.replyComments.length > this.visibleReplyCount;
    },
  },
  mounted() {
    this.likeCount = this.comment.likeCount;
    // 从本地存储获取用户ID（假设登录后存储了用户信息）
    this.userId = localStorage.getItem("id");
    this.checkLikeStatus();
    this.initialRequestParams();
  },
  methods: {
    reply() {
      // 获取评论内容和发布者
      const commentContent = this.comment.comment;
      const userName = this.comment.userName;

      // 弹出确认框
      ElMessageBox.prompt(
          `您正在回复：${userName} 的评论\n\n"${commentContent}"`,
          "回复评论",
          {
            confirmButtonText: "回复",
            cancelButtonText: "取消",
            inputType: "textarea", // 将输入框改为多行文本框
            inputPlaceholder: "请输入评论，限制最高500字，评论内容不能为空",
            inputValidator: (value) => {
              // 验证输入内容
              if (!value) {
                return "评论内容不能为空";
              }
              if (value.length > 500) {
                return "评论内容不能超过500字";
              }
              return true; // 输入内容有效
            },
            inputErrorMessage: "评论内容不能超过500字",
            inputAttrs: {
              rows: 5, // 设置文本框的行数为 5 行
            },
            beforeClose: (action, instance, done) => {
              if (action === "confirm") {
                // 用户点击了“回复”按钮
                const inputValue = instance.inputValue; // 获取输入框的值
                if (!inputValue) {
                  // 输入内容为空
                  instance.inputErrorMessage = "评论内容不能为空";
                  instance.confirmButtonLoading = false;
                  return;
                }
                if (inputValue.length > 500) {
                  // 输入内容超过500字
                  instance.inputErrorMessage = "评论内容不能超过500字";
                  instance.confirmButtonLoading = false;
                  return;
                }
                // 输入内容有效，执行回复逻辑
                const temp = this.comment;
                console.log(temp);
                axios.post("/comment/publish/reply", {
                  relatedCategory: this.relatedCategory,
                  relatedId: this.relatedId,
                  comment: instance.inputValue,
                  rootCommentId: temp.commentId,
                  replyUserName: temp.userName,
                })
                    .then((res) => {
                      if (res.data.data) {
                        ElMessage.success("回复成功");
                      } else {
                        ElMessage.error("回复失败：" + res.data.msg);
                      }
                    })
                    .catch((error) => {
                      ElMessage.error("回复失败：" + error.message);
                    });
                console.log("用户输入的评论内容：", inputValue);
                done(); // 关闭弹窗
              } else {
                // 用户点击了“取消”按钮
                done(); // 关闭弹窗
              }
            },
          }
      )
          .then((result) => {
            // 用户点击了“回复”按钮，且输入内容有效
            const replyContent = result.value;
            console.log("用户点击了回复按钮，回复内容为：", replyContent);
            // 在这里执行回复逻辑，例如发送回复内容到服务器
          })
          .catch(() => {
            // 用户点击了“取消”按钮
            console.log("用户取消了回复");
          });
    },
    formatDate(date) {
      if (!date) return "";
    },
    toggleReplies() {
      this.showReplies = !this.showReplies; // 切换子评论的显示状态
    },
    // 检查点赞状态
    async checkLikeStatus() {
      if (!this.userId) return;

      try {
        const response = await axios.get("/comment/checkLike", {
          params: {
            commentId: this.comment.commentId,
            userId: this.userId
          }
        });
        this.isLiked = response.data.data === 1;
      } catch (error) {
        console.error("检查点赞状态失败：", error);
      }
    },

    // 点赞操作防止多次点击
    handleLike: debounce(async function () {
      try {
        if (!this.userId) {
          ElMessage.warning("请先登录");
          return;
        }

        const response = await axios.post('/comment/likeChange/' + this.comment.commentId);
        this.isLiked = !this.isLiked;
        this.comment.likeCount += this.isLiked ? 1 : -1;
        ElMessage.success(response.data.data);
      } catch (error) {
        ElMessage.error("操作失败");
        console.error("点赞操作失败：", error);
        // 出现错误时回滚状态
        this.isLiked = !this.isLiked;
        // this.comment.likeCount += this.isLiked ? -1 : 1;
      }
    }, 300),
    initialRequestParams() {
      const query = this.$route.query;
      //判断是否为食堂店铺
      if (query.shopId !== undefined) {
        this.relatedId = query.shopId;
        this.relatedCategory = "食堂店铺";
      }
      //判断是否为教学楼信息
      if (query.contentId !== undefined) {
        this.relatedId = query.contentId;
        this.relatedCategory = "教学楼和学院楼";
      }
      //判断是否为舞萌中二条目
      if (query.mcId !== undefined) {
        this.relatedId = query.mcId;
        this.relatedCategory = "舞萌中二";
      }
      //判断是否为运动场条目
      if (query.playgroundId !== undefined) {
        this.relatedId = query.playgroundId;
        this.relatedCategory = "运动场";
      }
    },
    // 加载更多子评论
    loadMoreReplies() {
      this.visibleReplyCount += 3; // 每次点击增加3条子评论的显示数量
    },
  },

};
</script>

<style scoped>
.comment-item {
  border-bottom: 1px solid #f0f0f0;
  padding: 10px 0;
  font-size: 14px;
  line-height: 1.5;
}

.comment-header {
  display: flex;
  align-items: center;
  color: #666;
  margin-bottom: 5px;
}

.comment-header .user-name {
  font-weight: bold;
  color: #333;
  margin-right: 5px;
}

.comment-header .reply-info {
  margin-right: 5px;
}

.comment-header .reply-user {
  color: #1890ff;
}

.comment-header .create-time {
  margin-right: 5px;
}

.comment-content {
  margin-bottom: 5px;
  text-align: left;
}

.comment-actions {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.comment-actions .like-button,
.comment-actions .reply-button {
  margin-right: 10px;
}

.reply-item {
  margin-left: 20px;
  border-left: 1px solid #eaeaea;
  padding-left: 10px;
}

.load-more {
  text-align: center;
  margin-top: 10px;
  cursor: pointer;
}

.load-more a {
  color: #1890ff;
  text-decoration: underline;
}
</style>